﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WJP.Utils
{
    /// <summary>
    /// 帮助类
    /// </summary>
    public static class Helper
    {
        /// <summary>
        /// 忽略异常
        /// </summary>
        /// <param name="action"></param>
        public static void EatException(Action action)
        {
            try
            {
                action();
            }
            catch (Exception)
            {
            }
        }

        /// <summary>
        /// 忽略异常，发生异常时返回默认值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="action"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static T EatException<T>(Func<T> action, T defaultValue = default(T))
        {
            try
            {
                return action();
            }
            catch (Exception)
            {
                return defaultValue;
            }
        }

        /// <summary>
        /// 从指定的文件夹路径获取所有的程序集
        /// </summary>
        /// <param name="folderPath">文件夹路径</param>
        /// <param name="searchOption"></param>
        /// <returns></returns>
        public static List<Assembly> GetAllAssembliesInFolder(string folderPath, SearchOption searchOption)
        {
            if (!Directory.Exists(folderPath))
                return new List<Assembly>();

            var assemblyFiles = Directory
                .EnumerateFiles(folderPath, "*.*", searchOption)
                .Where(s => s.EndsWith(".dll") || s.EndsWith(".exe"));

            return assemblyFiles.Select(
                Assembly.LoadFile
            ).ToList();
        }

        /// <summary>
        /// 如果文件存在则删除文件
        /// </summary>
        /// <param name="filePath"></param>
        public static void DeleteIfExists(string filePath)
        {
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
        }
    }
}
